package cn.changein.framework.config.filter;

import cn.changein.framework.kernel.model.response.ResponseData;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * api 签名验证
 *

 */
@Slf4j
public class ApiSignatureFilter implements Filter {

    private final String API_SECRET;

    public ApiSignatureFilter(String apiSecret) {
        this.API_SECRET = apiSecret;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {
            /*HttpServletRequest request = (HttpServletRequest) servletRequest;
            String sign = request.getHeader("sign");
            if (StringUtils.isBlank(sign)) {
                onError("签名不能为空", response);
                return;
            }
            String reqTime = request.getHeader("reqTime");
            if (StringUtils.isBlank(reqTime)) {
                onError("请求时间不能为空", response);
                return;
            }
            *//*
            暂不校验
            Date date = DateUtils.parseDate(reqTime, "yyyy-MM-dd HH:mm:ss");
            if (Math.abs(date.getTime() - System.currentTimeMillis()) > 1000 * 60 * 30L) {
                //请求时间与当前时间相差30分钟，不通过
                onError("请求时间有误", response);
                return;
            }*//*
            String encrypt = MD5Util.encrypt(this.API_SECRET + ":" + reqTime);
            if (!sign.equalsIgnoreCase(encrypt)) {
                onError("签名错误", response);
                return;
            }*/
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            log.error("", e);
            onError("网络繁忙，请稍后再试！", response);
        }

    }

    private void onError(String msg, HttpServletResponse response) throws IOException {
        response.setStatus(500);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/json");
        response.getWriter().println(JSONObject.toJSONString(ResponseData.error(msg)));
    }
}
